import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './auth.controller';
import { UsersService } from "../users/users.service";
import { UserEntity } from "../users/entity/user.entity";

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
   private readonly  usersService:UsersService
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: jwtConstants.secret,
    });
  }

// 2. 系统自动验证token合法性，并将由token编译出的json作为参数传入validate方法中。
  async validate(payload: any) {
    const user = new UserEntity()
    //在jwt中取出账户id查询userid
    user.aId = payload.id
    const userRes = await this.usersService.usersFind(user)
    return userRes;
  }
}